var Router = require('express').Router();
var _ = require('underscore');
var db = require('../lib/db.js');
var ObjectID = require('mongodb').ObjectID;

var testCol = null;
function getTestCol(){
    testCol = testCol || db.getDb().collection('test');
    return testCol;
}

Router.get('/', function(req, res){
    var testCol = getTestCol();
    testCol.find({}).toArray(function(err, arr){
	if(err)
	    res.status(502).send('server error');
	else
	    res.status(200).json(arr);
    });
});

Router.get('/:id', function(req, res){
    var testCol = getTestCol();
    testCol.find({_id: ObjectID(req.params.id)}).toArray(function(err, docs){
	if(err)
	    res.status(502);
	else if(docs.length == 0)
	    res.status(404);
	else
	    res.status(200).json(docs);
    });
});

Router.delete('/:id', function(req, res){
    var testCol = getTestCol();
    testCol.remove({_id: ObjectID(req.params.id)}, function(err, result){
	if(err)
	    res.status(502).json(err);
	else
	    res.status(200).json(result);
    });
});

Router.put('/:id', function(req, res){
    var testCol = getTestCol();
    if(!req.body)
	res.status('404').send('no data transmitted');
    else{
	delete req.body._id;
	testCol.updateOne({_id: ObjectID(req.params.id)}, req.body, function(err, result){
	    if(err)
		res.status(502).json(err);
	    else
		res.status(200).json(result);
	});
    }
});

Router.post('/', function(req, res){
    var testCol = getTestCol();
    if(!req.body)
	res.status(404).send('no data transmitted');
    else{
	var id = new ObjectID();
	req.body._id = id;
	testCol.insert(req.body, function(err, result){
	    if(err)
		res.status(502).json(err);
	    else{
		_.extend(result, {_id: id});
		res.status(200).json(result);
	    }
	});
    }
});

module.exports = Router;
